What is the significance of the "base" keyword in C# and how is it used in inheritance?
What is the significance of the "base" keyword in C# and how is it used in inheritance?
38302-Jul-2023
Updated on 04-Jul-2023
Aryan Kumar
04-Jul-2023In C#, the
base
keyword is used to access members of the base class from within a derived class. It can be used to:For example, consider the following code:
C#
In this code, the
BaseMethod()
method is overridden in theDerivedClass
class. When theBaseMethod()
method is called on thederivedClass
object, the overridden version of the method is executed. However, if we want to call the original version of theBaseMethod()
method, we can use thebase
keyword. For example:C#
The
base
keyword can also be used to specify which base-class constructor should be called when creating instances of the derived class. For example:C#
In this code, the
DerivedClass
class has two constructors. The default constructor calls theBaseClass
constructor, and the parameterized constructor does not call theBaseClass
constructor. When we create aDerivedClass
object without passing any parameters, the default constructor is called. However, if we pass a parameter to theDerivedClass
constructor, the parameterized constructor is called, and theBaseClass
constructor is not called.The
base
keyword is a powerful tool that can be used to access members of the base class from within a derived class. It can be used to call methods, specify constructors, and more.